package com.chisheng.caa.util;

import com.fasterxml.jackson.databind.json.JsonMapper;
import lombok.SneakyThrows;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.nio.charset.StandardCharsets;
import java.util.Objects;

/**
 * Web 工具类
 */
public final class WebUtil {

    /**
     * Java 对象序列化器。
     */
    private final static JsonMapper JSON_MAPPER = new JsonMapper();

    private WebUtil() {
        throw new UnsupportedOperationException();
    }

    /**
     * 将 Java 对象以 JSON 格式渲染到客户端
     */
    @SneakyThrows
    public static void renderJson(HttpServletResponse response, Object obj) {
        response.setStatus(HttpStatus.OK.value());
        response.setContentType(MediaType.APPLICATION_JSON_VALUE);
        response.setCharacterEncoding(StandardCharsets.UTF_8.name());
        response.getWriter().print(JSON_MAPPER.writeValueAsString(obj));
    }

    /**
     * 判断是否为 AJAX 请求
     */
    public static boolean isAjaxRequest(HttpServletRequest request) {
        String flag = request.getHeader("X-Requested-With");
        return !Objects.isNull(flag) && "XMLHttpRequest".equals(flag);
    }

}